package nodes

import (
	"homeserver/logs"
	"net"
	"io"
	"io/ioutil"
	"encoding/json"
	"homeserver/worker"
)


// 设备服务配置地址
type SevBridgeConf struct {
	NodeAddress 	string		`json:"bridge_test_address"`
	NodeEnable		bool		`json:"bridge_test_enable"`
}

// 配置文件
var (
	sever_conf_file = "conf/services.json"
)

//
// 测试节点
//
func StartService(end chan bool)  {
	logs.Notice("node service: establish")

	// 获取设备服务IP地址
	buf, err := ioutil.ReadFile(sever_conf_file)
	if err != nil {
		logs.Err("services.conf not found!")
		end <- true
		return
	}

	var sev_conf SevBridgeConf
	err = json.Unmarshal(buf, &sev_conf)
	if err != nil || sev_conf.NodeAddress == "" {
		logs.Err("sevice node test conf err!")
		end <- true
		return
	}

	if sev_conf.NodeEnable == false {
		return
	}

	l, err := net.Listen("tcp", sev_conf.NodeAddress)
	if err != nil {
		logs.Err("node service estabish err: %s", err)
		end <- true
	}

	//
	// 订阅设备发送的通知消息
	//

	for {
		conn, err := l.Accept()
		if err != nil {
			logs.Err("node service accept err: %s", err)
			end <- true
		}

		go HandleNode(conn)
	}
}

//
// 解释节点数据输入
//
func HandleNode(conn net.Conn)  {
	defer conn.Close()

	for {
		buffer := make([]byte, 1024)
		n, err := conn.Read(buffer)
		if err != nil || err == io.EOF {
			return
		}

		logs.Info("node: %s", buffer[:n])

		var node_packet nodePacket
		err = json.Unmarshal(buffer[:n], &node_packet)

		if err != nil {
			return
		}

		data, _ := json.Marshal(node_packet.Data)


		// 请求消息，发送给设备处理
		if node_packet.Type == DEVICE_REQUEST {
			worker.RequestDevice(data)
		}

		// 通知消息，发送给设备通知家庭
		if node_packet.Type == DEVICE_NOTIFY {
			worker.DeviceNotify("", data)
		}

	}

}